package com.ssm.controller;

import com.ssm.pojo.User;
import com.ssm.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("/list")
    public String list(){
        return "user/user";
    }

    @RequestMapping("/listdata")
    @ResponseBody
    public Map<String,Object> listData(Integer page, Integer limit, String username){
        List<User> users = userService.selectUserPage(page,limit,username);
        Integer count = userService.countSize(username);

        // 返回表格数据
        Map<String,Object> resultMap = new HashMap<String, Object>();
        resultMap.put("code",0);
        resultMap.put("msg","");
        resultMap.put("count",count);
        resultMap.put("data",users);
        return resultMap;
    }

    @RequestMapping(value = "add",method = RequestMethod.GET)
    public String toAdd(){
        return "user/user_new";
    }

    @RequestMapping(value = "add",method = RequestMethod.POST)
    @ResponseBody
    public Map<String,String> add(User user){
        User user1 = userService.selectUserByName(user.getUsername());
        Map<String,String> map = new HashMap<String, String>();
        if(user1==null){
            userService.insert(user);
            map.put("status","true");
            map.put("msg","添加成功");
        }else {
            map.put("status","false");
            map.put("msg","用户已经存在");
        }
        return map;
    }

    @RequestMapping(value = "update",method = RequestMethod.GET)
    public String toUpdate(Model model,String username){
        User user = userService.selectUserByName(username);
        model.addAttribute("user",user);
        return "user/user_update";
    }

    @RequestMapping(value = "update",method = RequestMethod.POST)
    public String update(User user){
        userService.update(user);
        return "user/user";
    }

    @RequestMapping(value = "delete",method = RequestMethod.POST)
    @ResponseBody
    public Map<String,String> delete(String username){
        userService.delete(username);
        Map<String,String> map = new HashMap<String, String>();
        map.put("status","true");
        map.put("msg","删除成功啦");
        return map;
    }
}
